import axios from 'axios'
class HttpRequest {
  constructor(baseUrl = '', timeout = 30000) {
    this.baseUrl = baseUrl
    this.timeout = timeout
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      timeout: this.timeout,
    }
    return config
  }
  interceptors(instance, url) {
    instance.interceptors.request.use(
      (config) => {
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    ),
      instance.interceptors.response.use(
        (res) => {
          res = JSON.parse(JSON.stringify(res))
          const { data, code, msg } = res.data
          if (code === 0) {
            console.log('统一收集异常')
          }
          return { data, code, msg }
        },
        (error) => {
          const originalRequset = error.config
          if (
            error.code === 'ECONNABORTED' &&
            error.message.indexOf('timeout') !== -1
          ) {
            return this.request(originalRequset)
          }
          let errorInfo = error.response
          if (!errorInfo) {
            const {
              request: { statusText, status },
              config,
            } = JSON.parse(JSON.stringify(error))
            errorInfo = {
              statusText,
              status,
              request: { requesttURL: config.url },
            }
          }
          console.log(errorInfo)
          return Promise.reject(error)
        }
      )
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
